import {createWebHistory,createRouter} from 'vue-router'
import Home from '../page/Home'
import Commodity from '../page/Commodity'
import Shop from '../page/Shop'
import Login from '../page/Login'
import register from '@/page/Login/register.vue'

    const routes = [
        {
            path:'/',
            redirect:'/login'
        },
        {
            // 登录页
            path:'/login',
            name:'login',
            component:Login
        },
        {
            // 注册页
            path:'/register',
            name:'register',
            component:register
        },
        {
            // 主页
            path:'/home',
            name:'home',
            component:Home,
            meta:{
                requireAuth:true
            }
        },
        {
            // 商品页
            path:'/commodity',
            name:'commodity',
            component:Commodity,
            meta:{
                requireAuth:true
            }
        },
        {
            // 商店页
            path:"/shop",
            name:'shop',
            component:Shop,
            meta:{
                requireAuth:true
            }
        }
    ]

const isAuth = ()=>{
    return !!sessionStorage.getItem('auth')
}
const router = createRouter({
    history:createWebHistory(process.env.BASE_URL),
    routes
})

router.beforeEach((to, from, next) => {
    // 遍历跳转的路由以及子路由，检测是否有需要验证的
    if (to.matched.some(record => record.meta.requireAuth)) {
      // 该路由需要登录
      if (!isAuth()) {
        // 未登录，跳转到登录页面
        next({ name:'login' });
      } else {
        // 已登录，继续访问
        next();
      }
    } 
    // 已登录用户试图访问登录页面时，重定向到主页
    else if (to.path === '/login' && isAuth()) {
      next({ path: '/home' });
    } 
    // 不需要验证的页面
    else {
      next();
    }
  });

export default router